package com.talkyun.utils;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;

public class StreamUtils {

    public static String readToString(InputStream ins) {
        try {
            return ins == null ? null : doReadToString(ins);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            close(ins);
        }
    }

    private static String doReadToString(InputStream ins) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 4);
        byte[] buf = new byte[1024];
        int num = ins.read(buf);
        while (num != -1) {
            baos.write(buf, 0, num);
            num = ins.read(buf);
        }
        return baos.toString("UTF-8");
    }

    private static void close(Closeable cls) {
        if (cls != null) {
            try {
                cls.close();
            } catch (IOException e) {
                // ignore
                throw new RuntimeException(e);
            }
        }
    }
}
